package zerdlib.swing.model;

import java.util.EventObject;

import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import logger2.colorer.gui.ColorerPanel;

import zerdlib.events.GenericListener;
import zerdlib.events.containers.ListChangeEvent;
import zerdlib.events.containers.ListenableList;

public class TableModelWrapper<E> extends AbstractTableModel implements TableModel {
	private static final long serialVersionUID = 8886551391051935053L;
	ListenableList<E> content = null;
	TableModelRowWrapper<E> rowModel;
	
	GenericListener listener = new GenericListener() {
		@Override
		public void onEvent(EventObject ev_) {
			ListChangeEvent ev = (ListChangeEvent)ev_;
			switch (ev.getType()) {
			case ListChangeEvent.ELEMENT_ADDED:
				fireTableRowsInserted(ev.getIndex(), ev.getIndex());
				break;
			case ListChangeEvent.ELEMENT_CHANGED:
				fireTableRowsUpdated(ev.getIndex(), ev.getIndex());
				break;
			case ListChangeEvent.ELEMENT_REMOVED:
				fireTableRowsDeleted(ev.getIndex(), ev.getIndex());
				break;
			case ListChangeEvent.INTERVAL_CHANGED:
				fireTableDataChanged();
				break;
			default:
				break;
			}
		}
	};
	
	public TableModelWrapper(ListenableList<E> content, TableModelRowWrapper<E> rowModel) {
		super();
		this.rowModel = rowModel;
		setDataList(content);
	}

	@Override
	public int getRowCount() {
		if(content == null)
			return 0;
		else
			return content.size();
	}

	@Override
	public int getColumnCount() {
		return rowModel.getColumnCount();
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return rowModel.isCellEditable(content.get(rowIndex), columnIndex);
	}
	
	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		return rowModel.getValueAt(content.get(rowIndex), columnIndex);
	}
	
	@Override
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		rowModel.setValueAt(aValue, content.get(rowIndex), columnIndex);
	}

	@Override
	public String getColumnName(int columnIndex) {
		return rowModel.getColumnName(columnIndex);
	}
	
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		return rowModel.getColumnClass(columnIndex);
	}
	
	public void setDataList(ListenableList<E> list) {
		if(content != null)
			content.removeListener(listener);
		if(list != null) {
			content = list;
			content.addListener(listener);
		}
		fireTableDataChanged();
	}
}
